<template>
  <!-- 《考勤》 -->
  <div class="tables">
    <!-- 搜索项 -->
    <div class="search_bar flexBet">
      <div class="btns flex">
        <div class="primaryBtn w114 mr12" @click="handleAdd">
          <svg-icon class-name="icon-img" icon-class="add_svg"/>
          <div>创建考勤</div>
        </div>
        <div class="normalBtn w114" @click="confirmexport">
          <svg-icon class-name="icon-img" icon-class="download_svg"/>
          <div>下载考勤</div>
        </div>
      </div>
      <div class="inputs flex">
        <div class="label">学生</div>
        <el-input
          style="width: 180px"
          class="inputstyle"
          v-model="queryParams.search"
          placeholder="请输入学生姓名/学号"
          clearable
          @keyup.enter.native="queryParamsSearch"
          @clear="queryParamsSearch"
        />
        <div class="primaryBorderBtn w88 mr12 ml24" @click="queryParamsSearch">
          搜索
        </div>

        <div class="normalBtn w88" @click="resetQueryParamsSearch">重置</div>
      </div>
    </div>

    <div class="data_table mt16" style="height: calc(100vh - 280px)">
      <!-- 问卷列表 -->
      <el-table
        v-if="!loading"
        border
        v-loading="loading"
        :data="list"
        height="100%"
      >
        <el-table-column
          fixed="left"
          show-overflow-tooltip
          label="学生（学号）"
          align="center"
          prop="courseName"
        >
          <template slot-scope="scope">
            {{ scope.row.studentName }}({{ scope.row.studentNum }})
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in labels"
          :key="index"
          show-overflow-tooltip
          :label="item.name"
          align="center"
          :prop="item.t"
        >
          <!-- 表头slot -->
          <template slot="header">
            <div>
              <div>{{ item.time }}</div>
              <div>{{ item.name }}</div>
            </div>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column
          fixed="right"
          show-overflow-tooltip
          label="操作"
          align="center"
          prop="branchName"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >编辑
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 创建考勤 -->
    <el-dialog
      v-loading="loading"
      title="创建考勤"
      :visible.sync="open"
      width="528px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @close="cancel()"
    >
      <el-form
        @submit.native.prevent
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="考勤日期" prop="assessmentTime">
          <el-date-picker
            @change="handleAssessmentTimeChange"
            style="width: 320px"
            value-format="yyyy-MM-dd"
            v-model="form.assessmentTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考勤节次" prop="attendanceIds">
          <el-checkbox-group v-model="form.attendanceIds">
            <div
              class="checkbox_group"
              v-for="(item, index) in attendanceList"
              :key="index"
            >
              <el-checkbox :disabled="item.disabled" :label="item.id">{{
                  item.attendanceName
                }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>

        <el-button v-preventReClick type="primary" @click="submitForm">
          开始
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑是 单个学生对多个考勤 -->
    <editAttendanceDia
      @refresh="getList"
      :open.sync="editAttendanceDia_open"
      :drawerStudentRow="editAttendanceDia_drawerStudentRow"
      :courseSchedulingId="courseSchedulingId"
    ></editAttendanceDia>
    <!-- 手动考勤是 创建考勤 后单个考勤ids对应多个学生 -->
    <manualAttendanceDia
      @refresh="getList('LabelsAndAttendanceIds')"
      :open.sync="manualAttendanceDia_open"
      :attendanceTeacherId="manualAttendanceDia_attendanceTeacherId"
      :courseSchedulingId="courseSchedulingId"
    ></manualAttendanceDia>
  </div>
</template>
<script>
import editAttendanceDia from './editAttendanceDia.vue'
import manualAttendanceDia from './manualAttendanceDia.vue'
import {
  addAttendance,
  attendanceStudentListByCourseScheduling,
  listattendance
} from '@/api/tea_studentGrade/attendance'

export default {
  components: { editAttendanceDia, manualAttendanceDia },
  props: {
    activeName: {
      type: String
    }
  },
  data() {
    return {
      status: ['正常', '请假', '早退', '迟到', '迟到&早退', '旷课'],
      data: [],
      list: [],
      labels: [],
      attendanceList: [],
      attendanceIds: [],
      loading: false,
      // 总条数
      total: 0,
      // 搜索条件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        search: ''
      },
      open: false,
      // 手动考勤
      manualAttendanceDia_open: false,
      manualAttendanceDia_attendanceTeacherId: '',
      // 编辑考勤
      editAttendanceDia_open: false,
      editAttendanceDia_drawerStudentRow: {},
      form: {
        assessmentTime: this.getCurrentDate(),
        attendanceIds: []
      },
      // 表单校验
      rules: {
        assessmentTime: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        attendanceIds: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('选择项不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    activeName: {
      handler(newValue) {
        if (newValue == 'normal_attendance') {
          this.courseSchedulingId = JSON.parse(
            localStorage.getItem('COURSE_INFO')
          ).courseSchedulingId
          this.getList('LabelsAndAttendanceIds')
        }
      },
      immediate: true // 这个选项确保handler在watcher被创建时立即调用
    }
  },
  mounted() {
  },
  methods: {
    // 编辑考勤
    handleEdit(row) {
      this.editAttendanceDia_drawerStudentRow = row
      this.editAttendanceDia_open = true
    },
    drawer_handleClose() {
      this.showDrawer = false
    },
    getCurrentDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 当考勤时间变化 刷新禁用
    handleAssessmentTimeChange() {
      this.form.attendanceIds = []
      let includes = []
      for (let j = 0; j < this.labels.length; j++) {
        if (this.labels[j].time == this.form.assessmentTime) {
          includes = [
            ...includes,
            ...this.labels[j].t
              .slice(15, this.labels[j].t.length)
              .split(',')
              .map((item) => {
                return item - 0
              })
          ]
        }
      }
      for (let i = 0; i < this.attendanceList.length; i++) {
        this.attendanceList[i].disabled = includes.includes(this.attendanceList[i].id);
      }
      this.$forceUpdate()
    },
    // 添加考勤
    async handleAdd() {
      // 先获取节次 主要获取节次的id
      // this.labels为当前所有考勤过的节次 [{id: 9 name: "第三节课" t: "lable75" time: "2025-02-24"}]
      // this.attendanceList为节次列表 用于禁用
      console.log('添加考勤', this.labels, this.form.assessmentTime)

      try {
        let res = await listattendance({
          pageNum: 1,
          pageSize: 9999
        })
        const { code, rows } = res
        if (code == 200) {
          if (rows.length > 0) {
            this.attendanceList = rows
            this.reset()
            this.open = true
            let includes = []

            for (let j = 0; j < this.labels.length; j++) {
              if (this.labels[j].time == this.form.assessmentTime) {
                includes = [
                  ...includes,
                  ...this.labels[j].t
                    .slice(15, this.labels[j].t.length)
                    .split(',')
                    .map((item) => {
                      return item - 0
                    })
                ]
              }
            }

            for (let i = 0; i < this.attendanceList.length; i++) {
              this.attendanceList[i].disabled = includes.includes(this.attendanceList[i].id);
            }
          } else {
            // 点击排课时提示：请联系学校管理员配置考勤信息
            this.$modal.msgWarning('请联系学校管理员配置考勤信息')
          }
        }
      } catch (error) {
        console.error(error)
      } finally {
      }
    },
    // 搜索按钮
    queryParamsSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 检索表单重置
    resetQueryParamsSearch() {
      this.queryParams = {
        search: ''
      }
      this.queryParamsSearch()
    },
    // 要避免检索表格 为零的情况 type为空用于普通检索
    // type为 LabelsAndAttendanceIds 用于生成表头和添加的时候禁用节次
    async getList(type) {
      console.log('getList', type)
      if (type == 'LabelsAndAttendanceIds') {
        this.queryParams = {
          search: ''
        }
      }
      this.loading = true
      try {
        let res = await attendanceStudentListByCourseScheduling(
          type == 'LabelsAndAttendanceIds' ? {} : this.queryParams,
          this.courseSchedulingId
        )
        const { code, data } = res
        this.data = data
        if (code == 200) {
          // 用于循环表头
          // labels类似结构{t:'正常',name:'label1'}  label为label+attendanceTeacherId
          let labels = []
          let attendanceIds = []
          let sum = null
          for (let i = 0; i < data.length; i++) {
            data[i].studentNum = data[i].list[0].studentNum
            if (sum == null || data[i].list.length > sum) {
              // 选数组里最多的进行循环
              sum = data[i].list.length
              labels = []
              attendanceIds = []
              for (let j = 0; j < data[i].list.length; j++) {
                labels.push({
                  t: `lable${data[i].list[j].assessmentTime}${data[i].list[j].attendanceIds}`,
                  id: parseInt(data[i].list[j].attendanceIds),
                  name: data[i].list[j].attendanceNames,
                  time: data[i].list[j].assessmentTime
                })
                attendanceIds = [
                  ...attendanceIds,
                  ...data[i].list[j].attendanceIds.split(',')
                ]
              }
            }
          }

          // 结构类似于{stuName:xxx,label1:'正常',label2:'迟到'}
          for (let i = 0; i < data.length; i++) {
            // 最终是为了循环列表
            for (let j = 0; j < data[i].list.length; j++) {
              for (let h = 0; h < labels.length; h++) {
                if (
                  `lable${data[i].list[j].assessmentTime}${data[i].list[j].attendanceIds}` ==
                  `${labels[h].t}`
                ) {
                  data[i][
                    `lable${data[i].list[j].assessmentTime}${data[i].list[j].attendanceIds}`
                    ] = this.status[data[i].list[j].status]
                  data[i].attendanceTeacherId =
                    data[i].list[j].attendanceTeacherId
                  data[i].id = data[i].list[j].id
                }
              }
            }
          }
          if (type == 'LabelsAndAttendanceIds') {
            this.attendanceIds = attendanceIds
            this.labels = labels
            this.$forceUpdate()
          }
          console.log(data)
          this.list = data
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    cancel() {
      this.open = false
      this.reset()
    },
    // 重置考勤表单
    reset() {
      this.form = {
        assessmentTime: this.getCurrentDate(),
        attendanceIds: []
      }
      this.resetForm('form')
    },
    // 新增考勤确认
    submitForm: function() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.loading = true
          let params = JSON.parse(JSON.stringify(this.form))
          params.attendanceIds = params.attendanceIds.join(',')
          params.courseSchedulingId = JSON.parse(
            localStorage.getItem('COURSE_INFO')
          ).courseSchedulingId

          try {
            let res = await addAttendance(params)
            const { code, data } = res
            if (code == 200) {

              this.open = false
              // 刷新表头
              // this.getList("LabelsAndAttendanceIds");
              this.manualAttendanceDia_open = true
              this.manualAttendanceDia_attendanceTeacherId = data
            }
          } catch (error) {
            console.error(error)
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 导出
    async confirmexport() {
      let obj = this.queryParams
      obj.courseSchedulingId = this.courseSchedulingId
      this.download(
        `/school/teacher/attendance/exportAttendanceStudent`,
        obj,
        `《${JSON.parse(localStorage.getItem('COURSE_INFO')).courseName}》${
          JSON.parse(localStorage.getItem('COURSE_INFO')).schedulingName
        }班考勤.xlsx`
      )
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-checkbox-group {
  overflow-y: auto;
  max-height: calc(100vh - 350px);
}

.mt16 {
  margin-top: 16px;
}

.mr12 {
  margin-right: 12px;
}

.ml24 {
  margin-left: 24px;
}

.tables {
  padding: 16px 24px;
  width: 100%;
}

.exportbtn {
  display: flex;
  justify-content: space-between;

  margin: 10px 0;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  -webkit-appearance: none;
  background-color: #fff;
  /* 滚动条背景颜色 */
  height: 8px;
  /* 滚动条高度 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: #bfbfbf;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #fff;
}
</style>
